package in.srain.cube.views.list;

import java.util.List;

import in.srain.cube.request.JsonData;

public abstract class PagedListDataModel<T> {

    private ListPageInfo<T> mListPageInfo;
    private boolean mIsBusy = false;

    public PagedListDataModel() {
        mListPageInfo = new ListPageInfo<>(20);
    }

    public PagedListDataModel(int numPerPage) {
        mListPageInfo = new ListPageInfo<>(numPerPage);
    }

    protected abstract void doQueryData();

    public void queryFirstPage() {
        checkPageInfo();
        mListPageInfo.reset();
        doQueryDataInner();
    }

    public void queryNextPage() {
        checkPageInfo();
        doQueryDataInner();
    }

    private void checkPageInfo() {
        if (null == mListPageInfo) {
            throw new IllegalArgumentException(" mListPageInfo has not been initialized.");
        }
    }

    private void doQueryDataInner() {
        if (!tryEnterLock()) {
            return;
        }
        doQueryData();
    }

    public void updateResult(JsonData rawData, List<? extends T> list) {
        mIsBusy = false;
        mListPageInfo.updateResult(rawData, list);
    }

    private boolean tryEnterLock() {
        if (mIsBusy) {
            return false;
        }
        mIsBusy = true;
        return true;
    }

    protected void unlockOnRequestFail() {
        mIsBusy = false;
    }

    public ListPageInfo<T> getListPageInfo() {
        return mListPageInfo;
    }

    public void reset() {
        mListPageInfo.reset();
    }

    public void onDestroy() {
        mListPageInfo.resetAndClearList();
    }
}